package linestrategy

import (
	"codejy/analysis"
	"codejy/analysis/lineanalysis"
	"codejy/globalfunc"
	"codejy/store"
	"codejy/structdef"
	"strconv"
	"strings"
)

func init() {
	globalfunc.RegisterFuncAll("IncrementDecrementCalculate", IncrementDecrementCalculate)
}

// 自增减策略
type IncrementDecrementStrategy struct {
}

// 注册策略
func init() {
	RegisterStrategy(&IncrementDecrementStrategy{})
}

// 判断
func (f *IncrementDecrementStrategy) getId() int {
	return lineanalysis.IncrementDecrement
}

func (f *IncrementDecrementStrategy) Execute(threadStore *structdef.ThreadStore) {
	code := threadStore.Code
	IncrementDecrementCalculate(threadStore, code.LineContent)
}
func IncrementDecrementCalculate(threadStore *structdef.ThreadStore, code string) string {
	//截取出变量
	variable := code[:len(code)-2]
	//获取变量的值
	variableValue, scope, p := store.Get3LevelVariable(threadStore, variable)
	if !p {
		//如果变量不存在报错
		panic("变量" + variable + "不存在")
	}
	//判断是++还是--
	if strings.HasSuffix(code, "++") {
		//如果是++,那么就加1
		atoi, _ := strconv.Atoi(variableValue.Value)
		variableValue.Value = strconv.Itoa(atoi + 1)
	} else {
		//如果是--,那么就减1
		atoi, _ := strconv.Atoi(variableValue.Value)
		variableValue.Value = strconv.Itoa(atoi - 1)
	}
	//判断scope是否是地址,如果是那么就需要修改实例的值
	if analysis.IsInstanceAddress(scope) {
		store.SetInstanceProp(threadStore, scope, variableValue)
	} else {
		//将变量的值更新
		store.ModifyVariableScope(threadStore, scope, variableValue)
	}
	return variableValue.Value
}
